package com.zgzg.shop.pay.base;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zgzg.shop.pay.base.enums.ApiCode;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;

@Data
@Accessors(chain = true)
public class Result<T> {

    protected Integer code;
    protected String msg;
    protected T data;


    public Result(ApiCode apiCode, T data) {
        this.code = apiCode.getCode();
        this.msg = apiCode.getMsg();
        this.data = data;
    }

    public Result(ApiCode apiCode) {
        this.code = apiCode.getCode();
        this.msg = apiCode.getMsg();
    }

    public Result(ApiCode apiCode, String explanation, T data) {
        this.code = apiCode.getCode();
        this.msg = explanation;
        this.data = data;
    }

    public Result(int code, String message) {
        this.code = code;
        this.msg = message;
    }

    public Result() {

    }

    public Result(T data) {
        this.code = ApiCode.OK.getCode();
        this.msg = ApiCode.OK.getMsg();
        this.data = data;
    }

    public static Result success() {
        return new Result(ApiCode.OK);
    }

    public static <T> Result buildData(Boolean success, String message) {
        return new Result()
                .setCode(success ? ApiCode.OK.getCode() : ApiCode.PUSH_FAIL.getCode())
                .setMsg(success ? ApiCode.OK.getMsg() : message);
    }

    public static <T> Result<T> success(T data) {
        Result<T> Result = new Result<T>(ApiCode.OK);
        Result.setData(data);
        return Result;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return ApiCode.OK.getCode().equals(this.code);
    }

    public static Result fail(ApiCode apiCode, String msg) {
        Result apiResult = new Result(apiCode);
        if (StringUtils.isNotBlank(msg)) {
            apiResult.setMsg(apiResult.getMsg() + ":" + msg);
        }
        return apiResult;
    }

    public static Result fail(ApiCode apiCode) {
        Result apiResult = new Result(apiCode);
        return apiResult;
    }
}
